package com.druid.job;

import com.druid.entity.ClashFile;
import com.druid.service.managementservice.IClashFileService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

@Log4j2
@Component
@EnableScheduling
public class ClashFileUpdateJob {

    @Autowired
    private IClashFileService clashFileService;
    @Value("${clash.store}")
    private String store;

    /**
     * 每天执行一次
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void scheduledTask() {

        List<ClashFile> list = clashFileService.lambdaQuery()
                .groupBy(ClashFile::getUrlLink, ClashFile::getSource)
                .orderByDesc(ClashFile::getCreateTime)
                .list();
        for (ClashFile clashFile : list) {
            try {

                // 获取文件存储路径
                String storePath0 = clashFile.getStoreAddress();
                // 删除文件
                if (storePath0 != null) {
                    File file = new File(storePath0);
                    if (file.exists())file.delete();
                }

                URL url = new URL(clashFile.getUrlLink());
                URLConnection connection = url.openConnection();
                String fileName = url.getFile().substring(url.getFile().lastIndexOf("/") + 1);

                // 定义文件存储路径
                String storePath = store + fileName;
                File file = new File(storePath);

                // 创建文件输出流
                try (OutputStream outputStream = new FileOutputStream(file)) {
                    // 从URL连接读取数据并写入文件
                    IOUtils.copy(connection.getInputStream(), outputStream);
                }
            }catch (Exception e){
                log.error("ClashFile更新失败",e);
            }

        }

    }
}
